<template>
  <a-modal
    v-model:visible="visible"
    :width="1000"
    wrap-class-name="role-menu-modal"
    :maskClosable="false"
    title="权限分配"
  >
    <a-spin :spinning="loading">
      <a-tabs v-model:activeKey="selMenuIndex">
        <a-tab-pane
          v-for="(firstMenu, firstMenuIndex) in menuList"
          :key="firstMenuIndex"
          :tab="firstMenu.title"
        >
          <table class="origin-table hadBorder">
            <thead>
              <tr>
                <th class="w-100 text-center">
                  <a-checkbox
                    v-model:checked="firstMenu.checked"
                    :indeterminate="firstMenu.indeterminate"
                    @change="
                      checkRecursion($event, firstMenu);
                      checkedSelect(firstMenuIndex);
                    "
                  >
                  </a-checkbox>
                </th>
                <th class="w-150 text-center">菜单</th>
                <th>权限</th>
              </tr>
            </thead>
            <tbody>
              <template
                v-for="secondaryMenu in firstMenu.children"
                :key="secondaryMenu.id"
              >
                <tr>
                  <td class="w-100 text-center">
                    <a-checkbox
                      v-model:checked="secondaryMenu.checked"
                      :indeterminate="secondaryMenu.indeterminate"
                      @change="
                        checkRecursion($event, secondaryMenu);
                        checkedSelect(firstMenuIndex);
                      "
                    >
                    </a-checkbox>
                  </td>
                  <td class="w-150 text-center font-weight-bold">
                    {{ secondaryMenu.title }}
                  </td>
                  <td>
                    <template
                      v-for="threeMenu in secondaryMenu.children"
                      :key="threeMenu.id"
                    >
                      <div class="btnMenu">
                        <a-checkbox
                          v-model:checked="threeMenu.checked"
                          @change="
                            checkRecursion($event, threeMenu);
                            checkedSelect(firstMenuIndex);
                          "
                        >
                          {{ threeMenu.title }}
                        </a-checkbox>
                      </div>
                    </template>
                  </td>
                </tr>
              </template>
            </tbody>
          </table>
        </a-tab-pane>
      </a-tabs>
    </a-spin>
    <template #footer>
      <a-button @click="cancel" :loading="loading">取消</a-button>
      <a-button type="primary" :loading="loading" @click="submit"
        >确定</a-button
      >
    </template>
  </a-modal>
</template>
<script lang="ts">
import { defineComponent, reactive, toRefs } from "vue";
import systemApis from "@/apis/system";
export default defineComponent({
  name: "RoleMenu",

  setup(props, { emit }) {
    const state = reactive({
      loading: false as boolean,
      visible: false as boolean,
      roleId: "" as string | number,
      menuList: [] as Array<any>,
      checkMenuList: [] as Array<any>,
      selMenuIndex: 0,
    });
    const open = (roleId: string | number) => {
      state.visible = true;
      state.roleId = roleId;
      getRoleAndMenu();
    };

    // 获取角色权限，并发查询所有菜单树以及角色所属菜单
    const getRoleAndMenu = async () => {
      try {
        state.loading = true;
        const roleRes: any = await systemApis.getMenuIdByRole(state.roleId);
        console.log(roleRes);
        if (roleRes.code !== 0) throw roleRes.msg || "接口请求出错";
        let authoritiesList: any = {};
        roleRes.data.forEach((item: any) => {
          authoritiesList[item] = 1;
        });
        const menuRes: any = await systemApis.menuTree();
        console.log(menuRes);
        if (menuRes.code !== 0) throw menuRes.msg || "接口请求出错";
        state.menuList = menuRes.data.map((fm: any, index: number) => {
          fm.checked = authoritiesList[fm.id] ? true : false;
          fm.children = fm.children.map((sm: any) => {
            sm.checked = authoritiesList[sm.id] ? true : false;
            sm.indeterminate = false;
            sm.children = sm.children.map((tm: any) => {
              tm.checked = authoritiesList[tm.id] ? true : false;
              return tm;
            });
            if (sm.children.length === 0) {
              sm.children.push({
                checked: authoritiesList[sm.id] ? true : false,
                title: "查看",
                id: sm.id,
                terminal: "1",
                key: sm.key,
                children: [],
              });
            } else {
              sm.children.unshift({
                checked: authoritiesList[sm.id] ? true : false,
                title: "查看",
                id: sm.id,
                terminal: "1",
                key: sm.key,
                children: [],
              });
            }
            return sm;
          });

          return fm;
        });
        state.menuList.map((item, index) => {
          checkedSelect(index);
        });
        state.loading = false;
        console.log("组合后数据", state.menuList);
      } catch (err) {
        state.loading = false;
      }
    };
    // 是否全部选中
    const checkedSelect = (menuIndex: any) => {
      state.menuList[menuIndex]?.children.forEach((sm: any) => {
        sm.children.forEach((tm: any) => {
          // 查看4级菜单是否有选中
          const fomChecked = tm.children.every(
            (item: any) => item.checked && !item.indeterminate
          );
          const fomNoChecked = tm.children.every(
            (item: any) => !item.checked && !item.indeterminate
          );
          if (tm.children.length > 0) {
            if (fomChecked) {
              tm.checked = true;
              tm.indeterminate = false;
            } else if (fomNoChecked) {
              tm.checked = false;
              tm.indeterminate = false;
            } else {
              tm.checked = false;
              tm.indeterminate = true;
            }
          }
        });
        // 查看3级菜单是否有选中
        const tmChecked = sm.children.every(
          (item: any) => item.checked && !item.indeterminate
        );
        const tmNoChecked = sm.children.every(
          (item: any) => !item.checked && !item.indeterminate
        );
        if (sm.children.length > 0) {
          if (tmChecked) {
            sm.checked = true;
            sm.indeterminate = false;
          } else if (tmNoChecked) {
            sm.checked = false;
            sm.indeterminate = false;
          } else {
            sm.checked = false;
            sm.indeterminate = true;
          }
        }
      });
      // 查看2级菜单是否有选中
      const fmChecked = state.menuList[menuIndex].children.every(
        (item: any) => item.checked && !item.indeterminate
      );
      const fmNoChecked = state.menuList[menuIndex].children.every(
        (item: any) => !item.checked && !item.indeterminate
      );
      if (state.menuList[menuIndex].children.length > 0) {
        if (fmChecked) {
          state.menuList[menuIndex].checked = true;
          state.menuList[menuIndex].indeterminate = false;
        } else if (fmNoChecked) {
          state.menuList[menuIndex].checked = false;
          state.menuList[menuIndex].indeterminate = false;
        } else {
          state.menuList[menuIndex].checked = false;
          state.menuList[menuIndex].indeterminate = true;
        }
      }
    };
    // 递归，
    const checkRecursion = (e: any, data: any) => {
      data.checked = e.target.checked;
      if (!data.children || (data.children && data.children.length === 0)) {
        return;
      }
      for (let i = 0, len = data.children.length; i < len; i++) {
        data.children[i].checked = e.target.checked;
        checkRecursion(e, data.children[i]);
      }
    };
    const cancel = () => {
      state.visible = false;
    };
    const submit = async() => {
      state.checkMenuList = []; // 初始化数据，避免出现脏数据
      // this.getCheckedNode(this.menuList); // 获取选中以及半选的节点
      state.menuList.forEach((first) => {
        if (first.checked || first.indeterminate) {
          state.checkMenuList.push(first.id);
        }
        first.children.forEach((second: any) => {
          if (second.checked || second.indeterminate) {
            state.checkMenuList.push(second.id);
          }
          second.children.forEach((three: any) => {
            if (three.checked || three.indeterminate) {
              state.checkMenuList.push(three.id);
            }
            three.children.forEach((four: any) => {
              if (four.checked || four.indeterminate) {
                state.checkMenuList.push(four.id);
              }
            });
          });
        });
      });
      state.loading = true;
      let checkMenuList = Array.from(new Set(state.checkMenuList));
      console.log("选中的菜单", checkMenuList);
      const res:any = await systemApis.updatePerm({roleId: state.roleId, menuIds: checkMenuList});
      console.log('结果是什么?')
      console.log(res)
      state.loading = false;
      if(res.code === 0) {
          cancel();
      }
    };
    return {
      open,
      cancel,
      checkedSelect,
      checkRecursion,
      submit,
      ...toRefs(state),
    };
  },
});
</script>
<style lang="less" scoped>
.btnMenu {
  width: 100px;
  display: inline-block;
}
</style>
<style lang="less">
.role-menu-modal {
  .ant-modal-body {
    padding: 0 24px 24px;
  }
}
</style>